#include <windows.h>
#include <assert.h>
#include <string.h>
#include "CeDatabase.hpp"

CCeDataBase::CCeDataBase()
{
	m_hDB = INVALID_HANDLE_VALUE;
}

CCeDataBase::~CCeDataBase()
{
	if(m_hDB!=INVALID_HANDLE_VALUE) {
		Close();
	}
}

bool CCeDataBase::Open(LPCTSTR pVolumeName, LPCTSTR pTableName)
{
	assert(!m_hDB);
	if(m_hDB) return false;

	CEGUID ceguid;
	TCHAR szName[MAX_PATH];

	CREATE_INVALIDGUID(&ceguid);
	bool bFound = false;
	while (::CeEnumDBVolumes(&ceguid, szName, MAX_PATH)) {
		if(_tcscmp(pVolumeName, szName)==0) {
			bFound = true;
			break;
		}
	}
	if(!bFound) return false;

	CEOID ceoid;
	ceoid = 0;
    CENOTIFYREQUEST *pRequest = (CENOTIFYREQUEST*)LocalAlloc(LPTR, sizeof(CENOTIFYREQUEST));
    pRequest->dwSize = sizeof(CENOTIFYREQUEST);
    pRequest->hwnd = NULL;
    pRequest->hHeap = NULL;
    pRequest->dwFlags = CEDB_EXNOTIFICATION;

	_tcscpy(szName, pTableName);
    m_hDB = ::CeOpenDatabaseEx(&ceguid, &ceoid, szName, 0, 0, pRequest);
	if(m_hDB==INVALID_HANDLE_VALUE) return false;

	return true;
}

bool CCeDataBase::Close()
{
	assert(m_hDB);
	if(!m_hDB) return false;

	HANDLE hDB = m_hDB;
	m_hDB = NULL;

	if(!CloseHandle(m_hDB)) {
		return false;
	}
	if(!CeFlushDBVol(&m_ceGuid)) {
		return false;
    }
	if(!CeUnmountDBVol(&m_ceGuid)) {
		return false;
    }
	return true;
}

DWORD CCeDataBase::GetFiledsCount()
{
	return 0;
}

DWORD CCeDataBase::GetFieldType(DWORD dwCol)
{
	return 0;
}

LPCTSTR CCeDataBase::GetFieldName(DWORD dwCol)
{
	return NULL;
}

DWORD CCeDataBase::GetRecordCount()
{
	return 0;
}

bool CCeDataBase::Goto(DWORD nIndex)
{
	return true;
}

LPCTSTR	CCeDataBase::GetFieldValue(DWORD dwCol)
{
	return NULL;
}
